<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ include file="/wesite/view/common/base.jsp" %>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>我的收藏</title>
    <%@ include file="/wesite/view/common/common.jsp" %>
    <style>
        .my-collect-bot span{
            display: block;
            width: 15.466667rem;
            height: 2.346667rem;
            background: #0daeff;
            border-radius: 5px;
            -webkit-border-radius: 5px;
            text-align: center;
            color: #fff;
            font-size: 0.8rem;
            line-height: 2.346667rem;
            margin:0 auto;
            margin-top: .43rem;
        }
        .btn-size{
            position: fixed;
            bottom:0;
            left: 0;
            width: 100%;
            /*padding: 0.875rem 2.3125rem;*/
            height: 3.375rem;
            background: #FFF;
            z-index: 13;
            border-top: 1px solid #e5e5e5;
        }
    </style>
</head>
<div>
    <div id="mainLayer" class="shopping-cart">
        <div class="hd">
            <div class="fl">
                <span>共：<i name="count"></i>件商品</span>
                <span>已选<i name="selectedProductCount">0</i>件</span>
            </div>
            <div class="fr">
                <span>
                    <input type="checkbox" name="" value="" id="allckb"/>
                    <i>全选</i>
                </span>
                <span onclick="delConfirm()">删除</span>
            </div>
        </div>
        <div class="cl"></div>
        <ul class="list">

        </ul>
    </div>
    <div class="h98 js-hover-layer"></div>
    <div class="my-collect-bot btn-size js-hover-layer">
        <span onclick="addToCart()">加入购物车</span>
    </div>

    <div class="empty-page" style="display: none;">
        <span class="txt-kong-img"><img src="${webctx}/images/Thome.png"></span>
        <%--<a href="javascript:location.href='/we/index'" class="go-shopping"><span>去挑选商品</span></a>--%>
        <p>您尚未收藏商品 <a href="javascript:location.href='/we/index'">点我去逛逛~</a></p>
    </div>
</div>
</body>
<script src="${ctx }/plugins/artTemplate/dist/template.js"></script>
<script type="text/javascript" src="${webctx}/script/aui-dialog.js"></script>
<script type="text/javascript" src="${webctx}/script/aui-scroll.js"></script>
<script type="text/javascript" src="${webctx}/script/common.js"></script>
<script type="text/javascript">
    //减少商品数量
    $('.list').on('click', '.sy_minus', function () {
        var txt = $(this).next();
        var n = parseInt(txt.val());
        n--;
        txt.val(n);
        inputAmount(txt);
    });

    //输入数量
    $('.list').on('change', '.num', function () {
        $(this).val($(this).val().replace(/[^0-9]/g, ''));
        if ($(this).val() == '0' || $(this).val() == '') $(this).val('1');
        if ($(this).attr("maxnum") && $(this).val()) {
            var max = parseInt($(this).attr("maxnum"));
            if (parseInt($(this).val()) > max) $(this).val(max);
        }
    });

    $('.list').on('focus', '.num', function () {
        $(this).select();
    });
    //增加商品数量
    $('.list').on('click', '.sy_plus', function () {
        var txt = $(this).prev();
        var n = parseInt(txt.val());
        n++;
        txt.val(n);
        inputAmount(txt);
    });

    //显示选择数
    $('.list').on('click', '.selectbox', function () {
        var txt = $("[name='selectedProductCount']").text();
        var n;
        if ($(this).find("input").is(":checked")) {
            n = parseInt(txt);
            n++;
            if ($(".list").find(":checked").length == $("[name='count']").text()) {
                $("#allckb").attr("checked", true);
            }
        } else {
            $("#allckb").attr("checked", false);
            n = parseInt(txt);
            n--;
        }
        $("[name='selectedProductCount']").text(n);
    });

    function delConfirm() {
        //确认删除
        new auiDialog({}).alert({
            title: "确认删除",
            buttons: ['取消', '确定']
        }, function (ret) {
            if (ret.buttonIndex == 2) {
                delFavorite();
            }
        })
    }

    //删除收藏
    function delFavorite() {
        var ids = $(".list").find(":checked").map(function () {
            return $(this).val();
        }).get();
        if (ids.length > 0) {
            $w.httpRequest({
                url: "${ctx}/we/favorite",
                data: {"_method": "DELETE", "ids": ids},
                ok: function () {
                    window.location.reload();
                },
                fail: function () {
                    new auiToast().fail({
                        title: "删除失败",
                        duration: 800
                    });
                }
            })
        } else {
            new auiToast().fail({
                title: "请选择商品",
                duration: 800
            });
        }
    }

    //加入购物车
    var cartSubmit = true;
    var toast = new auiToast({});
    var dialog = new auiDialog({})
    function addToCart() {
        var productArr = $(".list").find(":checked").map(function () {
            return $(this).val() + "_" + $(this).parents("li").find(".num").val();
        }).get();
        if (cartSubmit && productArr.length > 0) {
            cartSubmit = false;
            $w.httpRequest({
                url: "${ctx}/we/home/addToCart",
                data: {"idsAmounts": productArr},
                ok: function () {
                    new auiToast().success({
                        title: "加入购物车成功",
                        duration: 800
                    })
                },
                fail: function (ret) {
                    if(ret.MsgCode==4011) {
                        var h = "以下商品超过限购次数：<br/>";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            var name = list[i].name;
                            h += "\n\r" + (i + 1) + "、" + name;
                        }
                        dialog.alert({
                            title : h,
                            duration : 800
                        })
                        cartSubmit = true;
                        return false;
                    }
                    if(ret.MsgCode == 101) {
                        var h = "以下商品库存不足：<br/>";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            var name = list[i].name ;
                            h += "\n\r" + (i + 1) + "、" + name;
                        }
                        dialog.alert({
                            title : h,
                            duration : 800
                        })
                        cartSubmit = true;
                        return false;
                    }
                    if(ret.MsgCode == 103) {
                        var h = "以下商品不在您的区域范围内销售：<br/>";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            var name = list[i].name;
                            h += "\n\r" + (i + 1) + "、" + name;
                        }
                        dialog.alert({
                            title : h,
                            duration : 800
                        })
                        cartSubmit = true;
                        return false;
                    }

                    new auiToast().fail({
                        title: "加入购物车失败",
                        duration: 800
                    });
                },
                all: function () {
                    cartSubmit = true;
                }
            })
        } else {
            new auiToast().fail({
                title: "请选择商品",
                duration: 800
            });
        }
    }

    apiready = function () {
        api.parseTapmode();
    }

    /*全选*/
    $("#allckb").click(function () {
        if (this.checked) {
            $(".selectbox input:checkbox").attr("checked", true);
            $("[name='selectedProductCount']").text($("[name='count']").text());
        } else {
            $(".selectbox input:checkbox").attr("checked", false);
            $("[name='selectedProductCount']").text(0);
        }
    });

    var hotsLoading = false;
    var IPageNo = 1;
    var totalPage = 1;
    function loadProducts() {
        if (hotsLoading) {
            return false;
        } else {
            hotsLoading = true;
        }

        $w.httpRequest({
            url: apiroot + "/we/favorite",
            method: "get",
            data: {"pno": IPageNo},
            ok: function (ret) {
                hotsLoading = false;
                var data = ret.Data;
                var count = data.resultCount;
                console.log(data);
                $("[name='count']").text(count);
                if (count == 0) {
                    $(".empty-page").css("display", "block");
                    $(".shopping-cart").hide();
                    $(".btn-size").hide();
                }
                totalPage = data.pageCount;
                productdata = data.list;
                if (productdata.length > 0) {
                    for (var i = 0; i < productdata.length; i++) {
                        if (productdata[i].B_chanjia && productdata[i].B_chanjia.length > 11) {
                            productdata[i].B_chanjia = productdata[i].B_chanjia.substr(0, 11) + "...";
                        }
                    }
                    IPageNo++;
                    showProducts();
                } else {
                    $(".list").text("已加载全部");
                    IPageNo = 0;
                }
            }
        })
    }

    function replaceHtmlFileserver(html){

        if(html){

            var sourceHtml = html;
            var fsIndex = -1;
            var targetHtml = "";
            do{
                fsIndex = sourceHtml.indexOf(fileserver);
                if( fsIndex >= 0 ){
                    if( fsIndex != 0 ){
                        targetHtml += sourceHtml.substr( 0 , fsIndex );
                    }
                    targetHtml += getRandomFileserver();
                    if( ( fsIndex + fileserver.length ) < ( sourceHtml.length - 1 ) ){
                        sourceHtml = sourceHtml.substring( fsIndex + fileserver.length );
                    }
                } else {
                    targetHtml += sourceHtml;
                }
            } while ( fsIndex >= 0 );

            return targetHtml;

        }
        return html;
    }

    function showProducts() {
        var h = template('productHtml_list', {
            ctx: ctx,
            fileserver: getRandomFileserver(),
            isuserauth: isuserauth,
            islogin: islogin,
            list: productdata
        });
        var newHtml = replaceHtmlFileserver(h);
        $(".list").append(newHtml);
    }

    $(function () {
        loadProducts();
        var bottomHeight = $("div.h98").height() * 2;
        var scroll = new auiScroll({
            listen: true, //是否监听滚动高度，开启后将实时返回滚动高度
            distance: bottomHeight //判断到达底部的距离，isToBottom为true
        }, function (ret) {
            if (ret.isToBottom) {
                if (IPageNo > 0 && IPageNo <= totalPage) {
                    var toast = new auiToast({});
                    toast.loading({
                        title: "加载中",
                        duration: 300
                    }, function () {
                        setTimeout(function () {
                            toast.hide();
                        }, 300)
                    });

                    loadProducts();
                }
            }
        });
    });

</script>
<script type="text/html" id="productHtml_list">
    {{each list as value i}}
    <li>
        <div class="selectbox"><input type="checkbox" name="productid" value="{{value.id}}"></div>
        <div class="img">
            <a href="{{ctx}}/we/product/{{value.id}}">
                {{if value.status!=2}}
                <div class="not-available-tips">已下架</div>
                {{/if}}
                {{if value.status ==2 && value.amount <= 0}}
                <div class="not-available-tips">无货</div>
                {{/if}}
                {{if value.status ==2 && value.amount > 0 && value.canbuy}}
                <div class="not-available-tips"></div>
                {{/if}}
                <img src="{{fileserver}}{{value.photo}}" onerror="this.src='{{ctx}}/wesite/images/noimg.jpg'">
            </a>
        </div>
        <div class="con">
            <h3>{{value.productname}} {{value.name}}</h3>
            <div class="data">
                <p>厂家：{{value.b_chanjia}}</p>
                <p>规格：{{value.b_guige}}</p>
                <span class="price">
                    {{if !islogin}}
                        <i>登录可见</i>
                    {{else if !isuserauth}}
                        <i>审核通过可见</i>
                    {{else if value.canbuy && value.status==2 && value.amount > 0}}
                        <i>该商品不在销售区域内</i>
                    {{else if islogin && isuserauth}}
                        <i>¥{{value.price}}</i>
                    {{/if}}
                </span>
                <div class="count-box">
                    <i class="sy_minus">-</i>
                    <input class="num focus-auto-select" name="amount" type="number" maxnum="{{value.amount}}"
                           {{if value.amount> 0}}value="1" {{else}} value="0"{{/if}}>
                    <i class="sy_plus">+</i>
                </div>
            </div>
        </div>
    </li>
    {{/each}}
</script>
</html>